package 练习;


import 抽象数据类型.ListNode;

/**
 * Copyright (C) 2023 思创数码科技股份有限公司
 * <p/>
 * 版权所有
 * <p/>
 * 类名　　  : k个一组反转链表
 * 功能概要  :
 *
 * @Author : yangwk
 * @Date : 2024/3/16 0:16
 */
public class k个一组反转链表 {

    public static void main(String[] args) {
        ListNode root = new ListNode(1);
        root.next = new ListNode(2);
//        root.next.next = new ListNode(3);
//        root.next.next.next = new ListNode(4);
//        root.next.next.next.next = new ListNode(5);
        ListNode.printListNode(reverseKListNode(root, 2));
    }

    public static ListNode reverseKListNode(ListNode node, int k) {
        ListNode pre = null;
        ListNode current = node;
        ListNode next = current;
        ListNode first = null;
        while (current != null) {
            int temp = 0;
            // 到达最后一位
            while (temp < k && next != null) {
                temp++;
                next = next.next;
            }
            ListNode listNode = current;
            if (temp==k) {
               listNode = reverseListNode(current, next);
            }
            if (first == null) {
                first = listNode;
            }
            if (pre != null) {
                pre.next = listNode;
            }
            pre = current;
            current = next;
        }
        return first;
    }

    public static ListNode reverseListNode(ListNode node, ListNode endNode) {
        ListNode current = node;
        ListNode pre = null;
        ListNode next = current.next;
        while (current != endNode) {
            current.next = pre;
            pre = current;
            current = next;
            if (next != null) {
                next = next.next;
            }
        }
        return pre;
    }

}
